package com.WJY.controller;

import com.WJY.pojo.Book;
import com.WJY.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController  //相当于@Controller,@ResponseBody两个注解
@RequestMapping("/MyBook")
@CrossOrigin //用来解决跨域问题
public class BookWebController {

    private R success(Object data) {
        return new R(200, data);
    }

    private R failure(String msg) {
        return new R(500, msg);
    }

    @Autowired
    private BookService bookService;

    @GetMapping
    public R queryBookList() {
        List<Book> list = bookService.queryBookList();
        return list != null && !list.isEmpty() ? success(list) : failure("暂无内容");
    }

    @GetMapping("/{id}")
    public R queryBookById(@PathVariable String id) {
        Book book = bookService.queryBookById(Integer.parseInt(id));
        return book != null ? success(book) : failure("无id为" + id + "的书籍");
    }

    @GetMapping(params = "bookName")
    public R queryBookByBookName(String bookName) {
        List<Book> list = bookService.queryBookByBookName(bookName);
        return list != null && !list.isEmpty() ? success(list) : failure("暂无内容");
    }

    @DeleteMapping("/{id}")
    public R delBookById(@PathVariable int id) {
        int i = bookService.delBookById(id);
        return i > 0 ? success("删除成功") : failure("删除失败");
    }

    @PostMapping
    public R addBook(@RequestBody Book book) {
        int i = bookService.addBook(book);
        return i > 0 ? success("新增成功") : failure("新增失败");
    }

    @PutMapping
    public R updateBook(@RequestBody Book book) {
        int i = bookService.updateBook(book);
        return i > 0 ? success("修改成功") : failure("修改失败");
    }
}
